﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.Configuration;
using ASPItalia.ModelVirtualCasting.Common;
using ASPItalia.ModelVirtualCasting.ObjectModel;

namespace ASPItalia.ModelVirtualCasting.Web.Utils.Providers
{
    public class MVCMembershipProvider : MembershipProvider
    {

        public override string ApplicationName
        {
            get { return "/"; }
            set { }
        }

        public override bool ValidateUser(string username, string password)
        {
			password = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
            
			var ctx = ApplicationContext.Current.Users;
            return ctx.Count(user => user.Username.Equals(username) && user.Password.Equals(password)) == 1;
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
			password = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");

            var ctx = ApplicationContext.Current.Users;

            // creazione utente
            MembershipUser u = new MembershipUser(this.Name, username, username, email, passwordQuestion, string.Empty, true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);

            User user = new User();
            user.Username = username;
            user.Password = password;
            user.Email = email;
            ctx.InsertOnSubmit(user);

            // verifica duplicazione mail e username
			if (ctx.GetAll().Count(us => us.Email.Equals(email, StringComparison.InvariantCultureIgnoreCase)) > 0)
			{
				status = MembershipCreateStatus.DuplicateEmail;
				return null;
			}

			if (ctx.GetAll().Count(us => us.Username.Equals(username, StringComparison.InvariantCultureIgnoreCase)) > 0)
			{
				status = MembershipCreateStatus.DuplicateUserName;
				return null;
			}

            // update
            try
            {
                ctx.SubmitChanges();
            }
            catch
            {
                // segnalo l'errore
                status = MembershipCreateStatus.ProviderError;
                return null;
            }

            // creazione
            status = MembershipCreateStatus.Success;
            return u;
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            var ctx = ApplicationContext.Current.Users;
            User u = ctx.Where(x => x.Username.Equals(username)).FirstOrDefault();
            if (u == null)
                return null;

            return new MembershipUser(this.Name, username, username, u.Email, string.Empty, string.Empty, true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            return GetUser(providerUserKey.ToString(), userIsOnline);
        }

        public override bool EnablePasswordReset
        {
            get { return true; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return 0; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return 1; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return 5; }
        }

        public override int PasswordAttemptWindow
        {
            get { return 0; }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { return MembershipPasswordFormat.Hashed; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return string.Empty; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return false; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return true; }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
			totalRecords = ApplicationContext.Current.Users.GetAll().Count();

			MembershipUserCollection users = new MembershipUserCollection();
			var myUsers = ApplicationContext.Current.Users.GetAll()
				.Select(u=> new MembershipUser(u.Username, u.Username, u.Username, u.Email, string.Empty, string.Empty, true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now))
				.Skip(pageIndex*pageSize).Take(pageSize).ToList();

			for (int i = 0; i < myUsers.Count; i++)
			{
				users.Add(myUsers[i]);
			}

			return users;
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
			var ctx = ApplicationContext.Current.Users;
			var user = ctx.GetAll().FirstOrDefault(u => u.Email.Equals(email, StringComparison.InvariantCultureIgnoreCase));

			if (user == null)
				throw new MembershipPasswordException("Cannot find the specified user");

			return user.Email;
        }

        public override string ResetPassword(string username, string answer)
        {
			string newPassword = GenerateRandomPassword();

			var ctx = ApplicationContext.Current.Users;
			var user = ctx.GetByUsername(username);

			if (user == null)
				throw new MembershipPasswordException("Cannot find the specified user");

			// salvataggio con hash
			user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(newPassword, "MD5");;

			try
			{
				ctx.SubmitChanges();
			}
			catch (Exception ex)
			{
				throw new MembershipPasswordException("Cannot reset the password. See inner exception.", ex);
			}

			return newPassword;
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

		private string GenerateRandomPassword()
		{
			// è possibile implementare un algoritmo più forte, se necessario
			// es: evitare sequenze e/o usare un dizionario per vietare termini noti
			return Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, MinRequiredPasswordLength);
		}
    }
}